var accountManagement = {
    // 查询列表接口
    params: {
        account: "",//帐号
        linkName: "",//联系人名称
        linkPhone: "",//手机号
        pageNumber: 1,//当前页
        pageSize: 20,//每页显示的数量
        providerId: '',//服务商id
        status: ''//状态（0:启用,1:禁用）
    },
    // 弹窗的接口入参
    modelParams: {
        account: '',// 帐号
        createUserName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,//创建人
        duties: '',//职务
        linkName: '',//联系人名称
        linkPhone: '',//联系人手机号
        mail: '',//邮箱
        providerId: '',// 服务商id
        providerName: '',//服务商名称
        updateUserName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name// 修改人
    },
    init: function () {
        this.addClick();
        this.getListsData();
    },
    addClick: function () {
        // 弹窗参数校验
        $('#form-model').Validform({
            tiptype: 2,
            callback:function(form){
                accountManagement.submitFn();
                return false
            }
        })

        // 服务商模糊查询
        $('.service-productName').on('keyup', function () {
            $('.search').show();
            accountManagement.searchServiceInfo($('#providerId').val())
        })
        // 选择服务商查询结果
        $('.search').delegate('.search-item', 'click', function () {
            var itemId = $(this).attr('data-id');
            var itemName = $(this).text();
            $('.service-productName').val(itemName);
            $('.search').hide();
            accountManagement.params.providerId = itemId;
        })

        // 弹窗-服务商模糊查询
        $('.model-service-productName').on('keyup', function () {
            $('.model-search').show();
            accountManagement.modelSearchServiceInfo($('#model-providerId').val())
        });
        // 模糊搜索失去焦点搜索结果框隐藏
        $(document).on('click',function(){
            $('.model-search').hide();
            $('.search').hide();
        })
        //  弹窗-服务商模糊查询
        $('.model-search').delegate('.model-search-item', 'click', function () {
            var itemId = $(this).attr('data-id');
            var itemName = $(this).text();
            $('.model-service-productName').val(itemName);
            $('.model-search').hide();
            accountManagement.modelParams.providerId = itemId;
            accountManagement.modelParams.providerName = itemName;
            $('#model-providerId').focus();
        })

        // 查询
        $('#searchBtn').on('click', function () {
            accountManagement.params.pageNumber = 1;
            accountManagement.params.pageSize = 20;
            accountManagement.params.account = $('#account').val();
            accountManagement.params.linkName = $('#linkName').val();
            accountManagement.params.linkPhone = $('#linkPhone').val();
            accountManagement.params.status = $("#status").find("option:selected").val();
            accountManagement.getListsData();

        })
        // 重置
        $('#resetBtn').on('click', function () {
            $('#account').val('')
            $('#linkName').val('')
            $('#linkPhone').val('')
            $('#providerId').val('')
            $('#status').val('')

            accountManagement.params.account = '';
            accountManagement.params.linkName = '';
            accountManagement.params.linkPhone = '';
            accountManagement.params.pageNumber = 1;
            accountManagement.params.pageSize = 20;
            accountManagement.params.providerId = '';
            accountManagement.params.status = '';

        })
        // 新增
        $('#addBtn').on('click', function () {
            // 清空校验
            $("#form-model").Validform().resetForm();
            $(".Validform_checktip .Validform_checktip ").html("");
            //新增
            $("#information").modal("show")
            $(".addressTitle").html("新增账号")
            $(".styleStatus").attr("disabled", false)
            $("#newlyAdded").css({
                display: "inline"
            })
            $("#see").css({
                display: "none"
            });
            //页面数据重置
            $('#model-providerId').val('')
            $('#model-account').val('')
            $('#model-linkName').val('')
            $('#model-duties').val('')
            $('#model-linkPhone').val('')
            $('#model-mail').val('')
        })
        // 弹窗 - 新增取消
        $('#cancelBtn').on('click', function () {
            $("#information").modal("hide");
        })
    },
    submitFn:function(){
        var flag = accountManagement.parameterChecked();
        if (flag) {
            if ($(".addressTitle").html() == '修改账号') {
                accountManagement.modelParams.account = $('#model-account').val();
                accountManagement.modelParams.linkName = $('#model-linkName').val();
                accountManagement.modelParams.duties = $('#model-duties').val();
                accountManagement.modelParams.linkPhone = $('#model-linkPhone').val();
                accountManagement.modelParams.mail = $('#model-mail').val();
                accountManagement.updateProviderAccountByIdInfo();
            } else {
                accountManagement.modelParams.account = $('#model-account').val();
                accountManagement.modelParams.linkName = $('#model-linkName').val();
                accountManagement.modelParams.duties = $('#model-duties').val();
                accountManagement.modelParams.linkPhone = $('#model-linkPhone').val();
                accountManagement.modelParams.mail = $('#model-mail').val();
                accountManagement.addProviderAccount();
            }
        }
    },
    getListsData: function () {
        var successData = function (data) {
            if (data.code == 0) {
                if (data.result.length > 0 && !!data.result) {
                    accountManagement.renderLists(data.result)
                    $(".M-box3").pagination({
                        pageCount: data.totalPage,
                        jump: true,
                        coping: true,
                        isHide: false,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function (api) {
                            accountManagement.params.pageNumber = api.getCurrent()
                            var successData = function (data) {
                                accountManagement.renderLists(data.result)
                            }
                            return web.doAjax(root.serviceProviderManagement.findProviderAccountByPage, 'post', accountManagement.params, successData, 1);
                        }
                    })
                } else {
                    $(".M-box3").pagination({
                        pageCount: 0
                    })
                    accountManagement.renderLists(data.result)
                }
            } else {
                $.Huimodalalert('数据异常', 2000);
            }

        }
        return web.doAjax(root.serviceProviderManagement.findProviderAccountByPage, 'post', accountManagement.params, successData, 1);
    },
    // 渲染列表
    renderLists: function (data) {
        var dataSource = [];
        $.each(data, function (index, item) {
            var obj = {};
            obj.id = item.id;// 序号
            obj.account = item.account; // 账号
            obj.linkName = item.linkName;// 联系人
            obj.linkPhone = item.linkPhone;// 手机号
            obj.providerName = item.providerName;// 服务商
            obj.createDate = item.createDate; // 创建时间
            obj.status = item.status; // 状态
            dataSource.push(obj)
        })
        accountManagement.lists(dataSource)
    },
    lists: function (data) {
        var datatable = $("#datatable").dataTable(); // 初始化dataTable，清空上一个值
        datatable.fnClearTable();//清空一下table
        datatable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            "order": [[1, "desc"]],
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": [5, 10, 25, 50],
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据"
            },
            data: data,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;" >' + row.id + '</span>';
                    },
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;" >' + row.account + '</span>';

                    },
                    "targets": 1
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;">' + row.linkName + '</span>';
                    },
                    "targets": 2
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;">' + row.linkPhone + '</span>';
                    },
                    "targets": 3
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;">' + row.providerName + '</span>';
                    },
                    "targets": 4
                },
                {
                    "render": function (data, type, row, meta) {
                        return '<span style="text-align: center;">' + row.createDate + '</span>';
                    },
                    "targets": 5
                },
                {
                    "render": function (data, type, row, meta) {
                        var status = '';
                        if (row.status == 0) {
                            status = '启用'
                        } else if (row.status == 1) {
                            status = '禁用'
                        }
                        return '<span style="text-align: center; cursor: pointer;color: blue;" onclick="accountManagement.switchStatus(' + row.id + ',' + row.status + ')">' + status + '</span>';
                    },
                    "targets": 6
                },
                {
                    "render": function (data, type, row, meta) {
                        return "<span style='text-align: center; color: blue; cursor: pointer' onclick='accountManagement.modifyDetail(" + row.id + ")'>修改</span>"
                            + "<span style='text-align: center; color: blue; margin-right: 10px; margin-left: 10px;cursor: pointer' onclick='accountManagement.queryDetail(" + row.id + ")'>查看详情</span>"
                            + "<span style='text-align: center; color: #0000ff;cursor: pointer;' onclick='accountManagement.resetPassWords(" + row.id + ")'>重置密码</span>"
                    },
                    "targets": 7
                },
            ],
        })
    },
    // 启用和禁用
    switchStatus: function (id, status) {
        if (status == 0) { // 启用
            layer.confirm('确定要禁用账号吗？', {
                btn: ['确认', '取消'] //按钮
            }, function (index) {
                accountManagement.updateProviderAccountStatusById(id, 1);
                layer.close(index)

            }, function () {
            });
        } else {
            layer.confirm('确定要启用账号吗？', {
                btn: ['确认', '取消'] //按钮
            }, function (index) {
                accountManagement.updateProviderAccountStatusById(id, 0);
                layer.close(index)
            }, function () {
            });
        }
    },
    // 新增确认
    addProviderAccount: function () {
        var providerId = accountManagement.modelParams.providerId;
        if(!providerId){
            $.Huimodalalert('服务商不存在,请重新选择', 2000);
            return false;
        }
        var successData = function (data) {
            if (data.code == 0) {
                $("#information").modal("hide");
                $.Huimodalalert('新增成功', 2000);
                accountManagement.getListsData();
            }else{
                $.Huimodalalert(data.msg, 2000);
            }
        }
        return web.doAjax(root.serviceProviderManagement.addProviderAccount, 'post', accountManagement.modelParams, successData, 1);
    },
    // 状态开启与禁用接口
    updateProviderAccountStatusById: function (id, status) {
        var params = {
            id: id,
            status: status
        }
        var successData = function (data) {
            if (data.code == 0) {
                $.Huimodalalert('修改成功', 2000);
                accountManagement.getListsData();
            }else{
                $.Huimodalalert('修改失败', 2000);
            }
        }
        return web.doAjax(root.serviceProviderManagement.updateProviderAccountStatusById, 'post', params, successData, 2);
    },
    // 修改确认
    updateProviderAccountByIdInfo: function () {
        var successData = function (data) {
            if (data.code == 0) {
                $("#information").modal("hide");
                $.Huimodalalert('修改成功', 2000);
                accountManagement.getListsData();
            }else{
                $.Huimodalalert(data.msg, 2000);
            }
        }
        return web.doAjax(root.serviceProviderManagement.updateProviderAccountById, 'post', accountManagement.modelParams, successData, 1);
    },
    //服务商模糊查询
    searchServiceInfo: function (name) {
        var params = {
            status: '',
            name: name
        }
        var successData = function (data) {
            if (data.code == 0 ) {
                if ( data.data && data.data.length > 0 ) {
                    var result = data.data;
                    var str = ''
                    result.forEach(function (item) {
                        str += '<li class="search-item" data-id="' + item.id + '">' + item.name + '</li>'
                    });
                    $('.search').html(str)
                } else {
                    var emptyStr = '<li class="search-item">暂无结果</li>';
                    $('.search').html(emptyStr)
                }
            }
        }
        return web.doAjax(root.serviceProviderManagement.findAll, 'post', params, successData, 2);
    },
    // 弹窗的服务商模糊查询
    modelSearchServiceInfo: function (name) {
        var params = {
            status: '',
            name: name
        }
        var successData = function (data) {
            if (data.code == 0) {
                if (data.data && data.data.length > 0) {
                    var result = data.data;
                    var str = ''
                    result.forEach(function (item) {
                        str += '<li class="model-search-item" data-id="' + item.id + '">' + item.name + '</li>'
                    });
                    $('.model-search').html(str)
                }
          /*      else {
                    var emptyStr = '<li class="model-search-item">暂无结果</li>';
                    $('.model-search').html(emptyStr)
                }*/

            }
        }
        return web.doAjax(root.serviceProviderManagement.findAll, 'post', params, successData, 2);
    },
    // 查看接口
    getProviderAccountByIdInfo: function (id) {
        var params = {
            id: id
        }
        var successData = function (data) {
            if (data.code == 0 && data.data) {
                var result = data.data;
                $('#model-providerId').val(result.providerName)
                $('#model-account').val(result.account)
                $('#model-linkName').val(result.linkName)
                $('#model-duties').val(result.duties)
                $('#model-linkPhone').val(result.linkPhone)
                $('#model-mail').val(result.mail)
                accountManagement.modelParams.providerId = result.providerId;
                accountManagement.modelParams.providerName = result.providerName;
            }

        }
        return web.doAjax(root.serviceProviderManagement.getProviderAccountById, 'post', params, successData);
    },
    // 重置密码
    reSetPasswordByIdInfo: function (id) {
        var params = {
            id: id
        }
        var successData = function (data) {
            if (data.code == 0) {
                layer.close(layer.index);
                $.Huimodalalert('修改成功', 2000);
            }
        }
        return web.doAjax(root.serviceProviderManagement.reSetPasswordById, 'post', params, successData);
    },
    // 查看详情按钮
    queryDetail: function (id) {
        accountManagement.getProviderAccountByIdInfo(id)
        //查看
        $("#information").modal("show")
        $(".addressTitle").html("查看账号")
        $(".styleStatus").attr("disabled", true)
        $("#newlyAdded").css({
            display: "none"
        });
        //重置提示状态
        $('.error-providerId').hide();
        $('.error-account').hide();
        $('.error-linkName').hide();
        $('.error-duties').hide();
        $('.error-linkphone').hide();
        $('.error-mail').hide();
    },
    // 修改
    modifyDetail: function (id) {
        accountManagement.getProviderAccountByIdInfo(id);
        accountManagement.modelParams.id = id;
        $("#information").modal("show")
        $(".addressTitle").html("修改账号")
        $(".styleStatus").attr("disabled", false)
        $("#model-providerId").attr("disabled", true)
        $("#newlyAdded").css({
            display: "inline"
        });
        //重置提示状态
        $('.error-providerId').hide();
        $('.error-account').hide();
        $('.error-linkName').hide();
        $('.error-duties').hide();
        $('.error-linkphone').hide();
        $('.error-mail').hide();
    },
    // 重置密码
    resetPassWords: function (id) {
        layer.confirm('是否确认重置密码？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            accountManagement.reSetPasswordByIdInfo(id);

        }, function () {
        });
    },
    //  参数校验
    parameterChecked:function(){
       var judgmentFieldObj = {
           serviceProduct:'请选择服务商',
           account:'请输入账号',
           linkName:'请输入姓名',
           linkPhone:'请输入手机号'
       }
       var params = {
           serviceProduct:$('.serviceProduct').val(),//服务商
           account:$('.account').val(),//账号
           linkName:$('.linkName').val(),//联系人
           linkPhone:$('.linkPhone').val(),//手机号
       }
        var isFlag = nullValueJudgmentFn(params,judgmentFieldObj);
        return isFlag
    }


}
accountManagement.init()